﻿using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wt.wine.Application.Common.Interfaces;
using wt.wine.Application.Common.Models;
using wt.wine.Domain.Entities;

namespace wt.wine.Application.ManageSkutable.Command
{
    /// <summary>
    /// 添加商品
    /// </summary>
    public class AddSkutableCommand : IRequest<Json<string>>
    {
        public string name { get; set; }
        public int price { get; set; }
        /// <summary>
        /// 目前固定值：50
        /// </summary>
        public int unit { get; set; }
        public string remark { get; set; }
    }

    public class AddSkutableCommandHandler : IRequestHandler<AddSkutableCommand, Json<string>>
    {
        private readonly IskutableRepository _iskutableRepository;
        private readonly ICurrentUserService _icurrentuserServices;
        public AddSkutableCommandHandler(IskutableRepository iskutableRepository, ICurrentUserService icurrentuserServices)
        {
            _iskutableRepository = iskutableRepository;
            _icurrentuserServices = icurrentuserServices;
        }
        public async Task<Json<string>> Handle(AddSkutableCommand request, CancellationToken cancellationToken)
        {
            int userid=_icurrentuserServices.GetUserId();
            if (userid <= 0)
            {
                return Json<string>.Failed("请先登录","");
            }
            else {
                if (string.IsNullOrWhiteSpace(request.name))
                {
                    return Json<string>.Failed("商品名称不能为空", "");
                }
                else if (request.name.Length > 50)
                {
                    return Json<string>.Failed("商品名称不能太长", "");
                }
                else if (request.price <= 0)
                {
                    return Json<string>.Failed("商品价格不能为0", "");
                }
                else if (request.unit <= 0)
                {
                    return Json<string>.Failed("零售价单位不能为0", "");
                }
                else
                {
                    skutable model = new skutable();
                    model.name = request.name;
                    model.price = request.price;
                    model.unit = request.unit;
                    model.userid = userid;
                    model.userpid = userid;
                    model.state = 0;
                    model.createtime = DateTime.Now;
                    model.updatetime = DateTime.Now;
                    model.remark = request.remark + "";
                    await _iskutableRepository.AddSkutable(model, cancellationToken);
                    return Json<string>.Success("添加成功","");
                }

            }
        }
    }
}
